/**
 * Created by james on 2018/11/9.
 */
var sjptyhtb = "";
var mdmyhtb = "";
var typing = false;

//外部js调用
laydate({
    elem: '#csrq',
    event: 'focus'
});

$(document).ready(function () {
    $('#ryxm').on('compositionstart', function () {
        typing = true;//中文输入法开始
    }).on('compositionend', function () {
        typing = false;//中文输入法结束
    }).on("keyup", function () {
        if(typing){
            return;
        }
        var _this = this;
        $(_this).val($(_this).val().replace(/[^a-zA-Z|\u4e00-\u9fa5]/ig,''));
    });
    $('#qyzt').lc_switch("正常","锁定");//初始化switch开关
    initDict(); //初始化下拉字典
    initZdyDict();
    initYhtb();

    $("#dldm").empty();
    $("#password").empty();
    $("#password1").empty();
});

/**
 * 初始化下拉框数据源
 * */
function initDict() {
    Common.GetSjyzy("CV08.30.005", "zc"); //职称
    Common.GetSjyzy("GB/T 2261.1-2003", "xb"); //性别
    Common.GetSjyzy("czry_yhlx","rylx");
}

/**
 *  初始化无法从数据元值域目录公用字典获取的下拉框
 * */
function initZdyDict() {

    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        url: "user/queryDict",
        cache: false,
        async: false,
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成功
                var list = jsonData.list;
                var optionhtml = '<option  value="" >--请选择--</option>';
                if (list.length > 0) {
                    for (var i = 0; i < list.length; i++) {
                        var data = list[i];
                        optionhtml += '<option value= "' + data.zdm + '" >' + data.zmc + '</option>';
                    }
                }
                $('#zwbm').append(optionhtml);
                var type = Common.GetRequest().type;
                if (type == "add") {
                    $("#dldm").val('');
                    $("#password").val('');
                    $("#password1").val("");
                    $("#mmxgsj").val("");
                    initView();
                } else {
                    getUserByZclsh();
                }

            } else {
                LayerWn.showFailAlert(jsonData.msg);
            }
        }
    });

    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        cache: false,
        async: false,
        url: "organization/queryDownZcjg/" + decodeURIComponent(Common.GetRequest().jgbm),
        success: function (jsonData) {
            if (jsonData.code == 200) {
                var list = jsonData.zcjg;
                var optionhtml_zcjg = '<option  value= ""></option>';
                if (list.length > 0) {
                    for (var i = 0; i < list.length; i++) {
                        optionhtml_zcjg += '<option  value= "' + list[i].jgbm + '" >' + list[i].jgmc + '</option>';
                    }
                }
                $('#jgbm').append(optionhtml_zcjg);//所属机构
            } else {
                LayerWn.showFailAlert(jsonData.msg);
            }
        }
    });
}

/**
 * 初始化用户同步参数
 * */
function initYhtb(){
    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        cache: false,
        async: false,
        url: "commonapi/queryQjcs/" + 'plat_sjptyhtb',
        success: function (jsonData) {
            if (jsonData.code == 200) {
                if (jsonData.qjcsEntity != null && jsonData.qjcsEntity.csz == "1") {
                    sjptyhtb = jsonData.qjcsEntity.csz;
                    $("#formOther1").css('display','block');
                    $("#labDzyx span").css('display','inline');
                }
            }
        }
    });

    $.ajax({
        type: "GET",
        contentType: 'application/json',
        dataType: "json",
        cache: false,
        async: false,
        url: "commonapi/queryQjcs/" + 'plat_mdmyhtb',
        success: function (jsonData) {
            if (jsonData.code == 200) {
                if (jsonData.qjcsEntity != null && jsonData.qjcsEntity.csz == "1") {
                    mdmyhtb = jsonData.qjcsEntity.csz;
                    $("#formOther1").css('display','block');
                    // $("#labSfzh span").css('display','none');
                    // $("#labSjhm span").css('display','none');
                }
            }
        }
    });
}

/***
 * 根据注册流水号获取用户信息
 * */
function getUserByZclsh() {
    var zclsh = Common.GetRequest().zclsh; //获取传入的用户主键值
    if (zclsh) {
        $.ajax({
            type: "GET",
            contentType: 'application/json',
            dataType: "json",
            url: "user/queryUser/" + zclsh,
            success: function (jsonData) {
                if (jsonData.code == 200) {   //查询成功

                    $('#userForm').populateForm(jsonData.us);
                    $("#dldm").attr("readOnly", true);
                    $("#mmxgsj").val(jsonData.us.mmxgsj);
                    $("#password").val(jsonData.us.password);
                    $("#password1").val(jsonData.us.password);

                    var qyzt=jsonData.us.qyzt;
                    if(qyzt=='N'){
                        $("#qyzt_switch").removeClass('lcs_on').addClass('lcs_off');
                    } else {
                        $("#qyzt_switch").removeClass('lcs_off').addClass('lcs_on');
                    }

                    initView();
                } else {
                    LayerWn.showFailAlert(jsonData.msg);
                }
            }
        });
    } else {
        $("#dldm").empty();
        $("#password").empty();
        $("#password1").empty();
        $("#mmxgsj").empty();
    }
}


/**
 * 数据校验
 */
function validate() {
    var result = true;
    /*if (!Common.isPoneAvailable($("#dhhm").val())) {
        LayerWn.showAlert('电话号码无效');
        return false;
    }*/

    //联系电话校验
    var dhhm = $.trim($("#dhhm").val());
    if (dhhm != '') {
        if (!Common.telValidate(dhhm)) {
            LayerWn.showAlert('电话号码不合规则');
            return false;
        }
    }

    var ryxm = $.trim($("#ryxm").val());
    if (ryxm == '') {
        LayerWn.showAlert('用户姓名不能为空');
        return false;
    }

    var jgbm = $.trim($("#jgbm").val());
    if (jgbm == '') {
        LayerWn.showAlert('机构名称不能为空');
        return false;
    }
    var dldm = $.trim($("#dldm").val());
    if (dldm == '') {
        LayerWn.showAlert('登录账号不能为空');
        return false;
    }

    var password = $.trim($("#password").val());
    if (password == '') {
        LayerWn.showAlert('登录密码不能为空');
        return false;
    }

    var rylx = $.trim($("#rylx").val());
    if (rylx == '') {
        LayerWn.showAlert('人员类型不能为空');
        return false;
    }

    var dzyx = $.trim($("#dzyx").val());
    if(sjptyhtb == '1' || mdmyhtb == '1') {
        if(sjptyhtb == '1') {
            var sjhm = $.trim($("#sjhm").val());
            if (sjhm == '') {
                LayerWn.showAlert('手机号码不能为空');
                result = false;
            } else {
                if (!Common.isPoneAvailable(sjhm)) {
                    LayerWn.showAlert('手机号码不合规则');
                    return false;
                }
            }
        }

        var sfzh = $.trim($("#sfzh").val());
        if (sfzh == '') {
            if(sjptyhtb == '1') {
                LayerWn.showAlert('身份证号不能为空');
                result = false;
            }
        } else {
            var pass = Common.jySfzh(sfzh);
            if (pass) {
                var xbdm = Common.jsXb(sfzh);
                $("#xb").val(xbdm);
                var csrq = Common.jsCsrqYMD(sfzh);
                $("#csrq").val(csrq);
            } else {
                result = false;
            }
        }

        if(sjptyhtb == '1') {
            if (dzyx == '') {
                LayerWn.showAlert('邮箱不能为空');
                result = false;
            }
        }
    }
    if(dzyx != ""){
        var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
        if (!reg.test(dzyx)) {
            LayerWn.showAlert('邮箱格式错误');
            result = false;
        }
    }
  /*  else {
        /!**
         * 获取密码复杂度验证开关
         * *!/
        $.ajax({
            type: "GET",
            contentType: 'application/json',
            dataType: "json",
            cache: false,
            async: false,
            url: "commonapi/queryQjcs/" + 'plat_MMJYGZ',
            success: function (jsonData) {
                if (jsonData.code == 200) {
                    var jygz = jsonData.qjcsEntity.csz;
                    console.log("jygz:" + jygz);
                    console.log("password:" + password);
                    if (jygz != null && jygz != "") {
                        jygz = jygz.trim();
                        //reg=/^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/;
                        var reg = new RegExp(jygz);
                        if (!reg.test(password)) {
                            LayerWn.showAlert('登录密码不符合校验规则,请联系管理员');
                            result = false;
                        }
                    }
                }
            }
        });

        /!**
         * 获取密码有效期验证开关
         * *!/
        $.ajax({
            type: "GET",
            contentType: 'application/json',
            dataType: "json",
            cache: false,
            async: false,
            url: "commonapi/queryQjcs/" + 'plat_MMYYQ',
            success: function (jsonData) {
                if (jsonData.code == 200) {
                    var yyq = jsonData.qjcsEntity.csz;
                    if (yyq != null && yyq != '' && yyq != '0') {
                        yyq = yyq.trim();
                        var mmxgsj = $.trim($("#mmxgsj").val().substr(0, 19).replace(/-/g, "/").replace(/T/g, " "));
                        var password = $.trim($("#password").val());
                        var password1 = $.trim($("#password1").val());
                        if (password == password1) {
                            if (mmxgsj == null || mmxgsj == "" || mmxgsj.length == 0) {
                                LayerWn.showAlert('登录密码已过期，请修改密码');
                                result = false;
                            } else {
                                var dateEnd = new Date();//获取当前时间
                                var dateBegin = new Date(mmxgsj);
                                var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
                                var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
                                if (dayDiff > yyq) {
                                    LayerWn.showAlert('登录密码已过期，请修改密码');
                                    result = false;
                                }
                            }
                        }

                    }


                }
            }
        });
    }*/
    return result;
}

/**
 * 保存
 */
function save() {
    if (!validate())
        return;

    var url = "user/save";
    var type = Common.GetRequest().type;
    if (type == "update") {
        url = "user/update";
    }
    var data = $("form").serializeJson();
    if($("#qyzt_switch").hasClass("lcs_on")){
        data.qyzt='Y';
    }else if ( $("#qyzt_switch").hasClass("lcs_off")){
        data.qyzt='N';
    }

    data.dldm = $("#dldm").val();
    data.mmxgsj = $("#mmxgsj").val();
    var password = $.trim($("#password").val());
    var password1 = $.trim($("#password1").val());
    //若密码进行修改或者是新增用户的密码时，对密码进行非对称加密
    if (password != password1) {
        var sm4 = new SM4Util();
        var tempKey = getTempKey();
        password = sm4.encryptData_CBC(password, tempKey);
        data.tempKey = tempKey;
        data.password = password;
    }
    var formJSON = JSON.stringify(data);
    $("#btnSave").attr('disabled', true);

    $.ajax({
        type: "POST",
        contentType: 'application/json',
        dataType: "json",
        url: url,
        data: formJSON,
        success: function (jsonData) {
            $("#btnSave").removeAttr('disabled');
            if (jsonData.code == 200) {   //保存成功
                LayerWn.showSucAlert('保存成功');

                for (var k = 0; k < parent.frames.length; k++) {
                    if (parent.frames[k].frameElement.src.indexOf("plat-user.html") != -1)
                        parent.frames[k].queryList();
                }
                setTimeout(function () {
                    parent.layer.closeAll();
                }, 5000);
            } else {
                LayerWn.showFailAlert(jsonData.msg);
            }
        }
    });
}

/**
 * 取消按钮
 */
function cancel() {
    parent.layer.closeAll();
}

/**
 * 选择机构
 */
function selectJgbm() {
    LayerWn.openDialog("选择机构", "open-jg.html?paramId=jgbm&paramName=jgmc", 500, 400, $('body'));
}

function initView() {
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
}

(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(function () {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);

function getTempKey() {
    function shuffle() {
        var arr = ['1', 'r', 'Q', '4', 'S', '6', 'w', 'u', 'D', 'I', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
            'q', '2', 's', 't', '8', 'v', '7', 'x', 'y', 'z', 'A', 'B', 'C', '9', 'E', 'F', 'G', 'H', '0', 'J', 'K', 'L', 'M', 'N', 'O', 'P', '3', 'R',
            '5', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        return arr.sort(function () {
            return (Math.random() - .5);
        });
    };
    var verificationCode = "";
    var code = shuffle();
    for (var i = 0; i < 16; i++) {
        verificationCode += code[i];
    }
    return verificationCode;
}